﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Zj.BaiduPicSpider.Sys.EnumExtension
{
    /// <summary>
    /// 枚举帮助类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class EnumHelper<T>
        where T:struct
    {
        private static List<EnumValueModel> EnumValueModels=new List<EnumValueModel>();


        static EnumHelper()
        {
            Type type = typeof(T);

            if (!type.IsEnum)
            {
                throw new Exception("need to be enum");
            }
            
            var values = type.GetEnumValues();

            if (values != null && values.Length > 0)
            {
                foreach (var val in values)
                {
                    var name = type.GetEnumName(val);

                    var fieldInfo = type.GetField(name);
                    var attrs = fieldInfo.GetCustomAttributes(false);
                    string annotationStr = name;
                    if (attrs != null && attrs.Count() > 0)
                    {
                        var attr = attrs.FirstOrDefault(a => a.GetType() == typeof(DescriptionAttribute)) as DescriptionAttribute;
                        annotationStr = string.IsNullOrEmpty(attr.Description)? name:attr.Description;
                    }

                    EnumValueModels.Add(new EnumValueModel() { Name = name, Value = val, Annotation = annotationStr });
                }
            }
        }


        /// <summary>
        /// 获取该枚举所有的字段说明
        /// </summary>
        /// <returns></returns>
        public static List<EnumValueModel> GetEnumModels()

        {
            return EnumValueModels;
        }


        /// <summary>
        /// 获取枚举某字段的说明
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static EnumValueModel GetEnumModel(string name)

        {
            return EnumValueModels.FirstOrDefault(m=>m.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
        }
    }
}
